package com.l.controller.saoma;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.l.entity.Recharge;
import com.l.pay.alipay.AlipayConfig;
import com.l.pay.alipay.AlipaySubmit;
import com.l.pay.wxpay.WxPayConfig;
import com.l.pay.wxpay.WxPayCore;
import com.l.service.RechargeService;
import com.l.utils.Msg;
import com.l.utils.UtilDate;
import com.l.utils.XmlUtils;

/**
 * 扫码支付
 * @author
 *
 */
@RestController
public class SaomaController{
	@Autowired
	RechargeService rechargeService;
	/**
	 * 支付入口 生成订单号->创建支付订单->提交支付至相关支付平台
	 * 
	 * 
	 */
	@RequestMapping("/saomapay")
	public Msg saomapay(Recharge recharge) throws Exception {
		// 生成订单号
		String orderNumber = UtilDate.getOrderNum();
		// 充值订单创建成功
		recharge.setOrdernumber(orderNumber);
		if (rechargeService.add(recharge)) {
			/**
			 * 支付宝支付
			 */
			switch (recharge.getPayment()) {
			case 1:
				// 把请求参数打包成数组(第一种，不需要生成二维码)
				/*Map<String, String> sParaTemp = new HashMap<String, String>();
				sParaTemp.put("service", AlipayConfig.service);
				sParaTemp.put("partner", AlipayConfig.partner);
				sParaTemp.put("seller_id", AlipayConfig.seller_id);
				sParaTemp.put("_input_charset", AlipayConfig.input_charset);
				sParaTemp.put("payment_type", AlipayConfig.payment_type);
				sParaTemp.put("notify_url", AlipayConfig.notify_url);
				sParaTemp.put("return_url", AlipayConfig.return_url);
				sParaTemp.put("anti_phishing_key", AlipayConfig.anti_phishing_key);
				sParaTemp.put("exter_invoke_ip", AlipayConfig.exter_invoke_ip);
				sParaTemp.put("out_trade_no", orderNumber);
				sParaTemp.put("subject", orderNumber);
				sParaTemp.put("total_fee", recharge.getMoney());
				sParaTemp.put("body", "");
				Map map = AlipaySubmit.buildRequestPara(sParaTemp);
				List<String> keys = new ArrayList<String>(map.keySet());
				String prestr = "https://mapi.alipay.com/gateway.do?";
				for (int i = 0; i < keys.size(); i++) {
					String key = keys.get(i);
					String value = (String) map.get(key);

					if (i == keys.size() - 1) {// 拼接时，不包括最后一个&字符
						prestr = prestr + key + "=" + value;
					} else {
						prestr = prestr + key + "=" + value + "&";
					}
				}*/
				//（第二种，需要生成二维码）
				AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL,
						AlipayConfig.APPID, AlipayConfig.private_key,
						AlipayConfig.FORMAT, AlipayConfig.input_charset,
						AlipayConfig.ali_public_key, AlipayConfig.sign_type);
				AlipayTradePrecreateRequest ali_request = new AlipayTradePrecreateRequest();
				// SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
				AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
				model.setSubject("购买课程"); // 商品名称
				model.setOutTradeNo(orderNumber); // 商户订单号(自动生成)
				model.setTotalAmount(recharge.getMoney()); // 支付金额
				model.setTimeoutExpress("300m"); // 超时关闭该订单时间
				String postdata = JSONObject.toJSONString(model);
				ali_request.setBizContent(postdata);
				ali_request.setNotifyUrl(AlipayConfig.notify_url); // 回调地址
				AlipayTradePrecreateResponse responses = null;
				try {
					responses = client.execute(ali_request);
				} catch (AlipayApiException e) {
					e.printStackTrace();
				}
				String body = responses.getBody();
				System.out.println(body);
				JSONObject jsonObject = JSONObject.parseObject(body);
				String prestr = jsonObject.getJSONObject(
						"alipay_trade_precreate_response").getString("qr_code");
				return Msg.success().add("url", prestr);
			case 2:
				//微信支付
				// 把请求参数打包成数组
				Map<String, String> sArray = new HashMap<String, String>();
				sArray.put("appid", WxPayConfig.appid);
				sArray.put("mch_id", WxPayConfig.mch_id);
				sArray.put("device_info", WxPayConfig.device_info);
				sArray.put("body", "recharge");
				sArray.put("nonce_str", WxPayConfig.nonce_str);
				sArray.put("out_trade_no", orderNumber);
				BigDecimal b = new BigDecimal(recharge.getMoney());
				BigDecimal r = b.multiply(new BigDecimal("100"));
				String s=r.toString();
				if(s.indexOf(".") > 0){
					  s = s.replaceAll("0+?$", "");//去掉后面无用的零
					  s = s.replaceAll("[.]$", "");//如小数点后面全是零则去掉小数点
					}
				sArray.put("total_fee", s);
				sArray.put("notify_url", WxPayConfig.notify_url);
				sArray.put("trade_type", "NATIVE");
				String xml = XmlUtils.map2xmlBody(WxPayCore.buildRequestPara(sArray), "xml");
				URL url = new URL(WxPayConfig.service);
				URLConnection uc = url.openConnection();
				if (!uc.getDoOutput()) {
					uc.setDoOutput(true);// POST方式
				}
				OutputStream os = uc.getOutputStream(); // 输出流，写数据
				os.write(xml.getBytes());
				BufferedReader reader = new BufferedReader(new InputStreamReader(uc.getInputStream())); // 读取结果
				String result = "";
				String line;
				while ((line = reader.readLine()) != null) {
					result = result+line;
				}
				Map rs = XmlUtils.xmlBody2map(result, "xml");
				System.out.println(rs);
				String code_url = (String) rs.get("code_url");
				return Msg.success().add("url", code_url);
			default:
				break;
			}
			return Msg.success();
		}else{
			return Msg.fail();
		}
	}
}
